package com.droidclaimsurveyor.helper.service;

import java.io.InputStreamReader;
import java.io.Reader;

import org.apache.http.*;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.*;

import com.droidclaimsurveyor.helper.asyntask.ProgressAsynTask;


public class RestfulWebService<P, R> extends ProgressAsynTask<P, R> {
	public static final int HTTP_GET = 0;
	public static final int HTTP_POST = 1;
	
	private String serviceUrl;
	private ServiceMethod<R> serviceMethod;

	public RestfulWebService() {
	}
	
	public void setServiceUrl(String serviceUrl) {
		this.serviceUrl = serviceUrl;
	}
	
	public void setWebServiceMethod(ServiceMethod<R> serviceMethod) {
		this.serviceMethod = serviceMethod;
	}

	@Override
	protected R performTaskInBackground(P... parameters) throws Exception {
		R result = null;

		String methodName = serviceMethod.getName();
		setTaskId(methodName);
		int methodType = serviceMethod.getMethodType();
		HttpRequestBase httpRequest;
		if(methodType==RestfulWebService.HTTP_POST){
			HttpPost httpPost = new HttpPost(serviceUrl + methodName);
			String parameter = serviceMethod.getParameter();
			
			StringEntity se = new StringEntity(parameter);
			httpPost.setEntity(se);
			httpRequest = httpPost;
		}else{
			String parameter = serviceMethod.getParameter();
			String requestUrl = serviceUrl + methodName + parameter;
			httpRequest = new HttpGet(requestUrl);
		}

		httpRequest.setHeader("Accept", "application/json");
		httpRequest.setHeader("Content-type", "application/json");

		DefaultHttpClient httpclient = new DefaultHttpClient();
		HttpResponse response = httpclient.execute(httpRequest);
		
		String json = "";
		if(response.getEntity().getContentLength()>0){
			// stream reader object
	        Reader responseReader = new InputStreamReader(response.getEntity().getContent());
	        //create a buffer to fill if from reader
	        char[] buffer = new char[(int) response.getEntity().getContentLength()];
	        //fill the buffer by the help of reader
	        responseReader.read(buffer);
	        //close the reader streams
	        responseReader.close();
	
	        //for the employee json object
	        json = new String(buffer);
		}
				
		result = serviceMethod.mapResponse(json);

		return result;
	}

}